<template>
  <div class="page-wrap">
    <div class="top-wrap">
      <el-input placeholder="查询sql" v-model="sql">
        <template slot="prepend">
          <el-select v-model="sql" placeholder="请选择" @change="handleSelectChange">
            <el-option v-for="item in sqlList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
        <template slot="append"
          ><el-button @click="deleteFromSqlList" slot="append" icon="el-icon-delete"> 移除</el-button>
          <el-button @click="addToSqlList" slot="append" icon="el-icon-star-off"> 收藏</el-button>
          <el-button @click="addToDefault" slot="append" :icon="defaultSql != sql ? 'el-icon-location-outline' : 'el-icon-location'"> 默认</el-button
          ><el-button @click="getData" slot="append" icon="el-icon-search"> 开始检索</el-button></template
        >
      </el-input>
    </div>
    <div class="top-wrap">
      <el-button @click="showType = 'speed'">转数</el-button>
      <el-button @click="showType = 'state'">异常</el-button>
      <el-button @click="showType = 'vol'">电压</el-button>
    </div>
    <div class="spin-status">
      <el-table size="mini" border :data="dataList" highlight-current-row height="100%" style="width: 100%">
        <el-table-column fixed prop="PAGE_ROW_NUMBER" label="No" width="50" align="center" />
        <el-table-column fixed prop="timestamp" label="上传时间" width="106">
          <template slot-scope="scope"> {{ scope.row.timestamp | toTime }} </template>
        </el-table-column>
        <el-table-column fixed prop="Side" label="L/R" width="54" align="center" />
        <el-table-column fixed prop="SpinStartAddr" label="Start" width="54" align="center" />
        <el-table-column prop="SpinSpeed" label="SpinSpeed" width="4900">
          <template slot="header">
            <div style="display: flex">
              <div class="sub-item" v-for="ix in 100" :key="ix">{{ ix }}</div>
            </div>
          </template>
          <template slot-scope="scope"
            ><div style="display: flex">
              <div class="sub-item" v-for="(item, inx) in scope.row.SpinSpeed" :key="scope.$index + inx">
                <template v-if="showType == 'speed'"> {{ item }}</template>
                <template v-else-if="showType == 'state'"> {{ exceptZh[scope.row.SpinState[inx]] }}</template>
                <template v-else> {{ scope.row.SpinVol[inx] }}</template>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <template v-for="item in propList">
          <el-table-column :prop="item" :label="item" :width="customColWidth[item] || 110" :key="'t' + item" />
        </template> -->
      </el-table>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.pageNum"
      :page-sizes="[1000, 3000]"
      :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
    />
  </div>
</template>
<script>
import BlockTitle from '@/components/BlockTitle/index.vue'
import request from '@/utils/request'
import dayjs from 'dayjs'
// console.log(BlockTitle)
export default {
  name: 'RawData',
  components: {
    BlockTitle,
    Gap: {
      template: `<div style="width:10px"></div>`,
    },
    GapX: {
      template: `<div style="width:20px"></div>`,
    },
  },
  filters: {
    toTime(t) {
      return dayjs(t).format('MM-DD HH:mm:ss')
    },

    twoNum(e) {
      return (e < 10 ? '0' : '') + e
    },
    thrNum(e) {
      return ('000' + e).slice(-3)
    },
  },
  data() {
    return {
      showType: 'speed',
      exceptZh: ['断', '掉', '闲', '弱', '弱+', '障', ''],
      sqlList: [
        {
          value: `select  * from mqtt m where payload like '%SpinInfo%' and DateDiff(dd,newsj,getdate())=0 order by timestamp Desc`,
          label: '默认当天全部',
        },
      ],
      pageInfo: { pageSize: 1000 },
      currentPage: 1,
      customColWidth: {
        id: 150,
        PackType: 80,
        Side: 60,
        SpinStartAddr: 70,
        SpinNumber: 60,
      },
      workshops: ['车间1', '车间2', '车间3'],
      macLis: [],
      macDetail: {},
      currentSide: '左边',
      currentMac: '',
      currentWorkshop: '',
      dataList: [],
      propList: [],
      sql: `select  * from mqtt m where payload like '%SpinInfo%' and DateDiff(dd,newsj,getdate())=0 order by timestamp Desc`,
      defaultSql: `select  * from mqtt m where payload like '%SpinInfo%' and DateDiff(dd,newsj,getdate())=0 order by timestamp Desc`,
    }
  },
  computed: {},
  created() {
    const defaultSqlList = localStorage.getItem('sqlList')
    if (defaultSqlList) this.sqlList = JSON.parse(defaultSqlList)
    const defaultSql = localStorage.getItem('defaultSql')
    if (defaultSql) this.sql = this.defaultSql = defaultSql
  },
  mounted() {
    window.dj = dayjs
    //console.log(dayjs)
    this.getData()
  },
  methods: {
    async deleteFromSqlList() {
      const r = await this.$confirm('确定要移除当前sql吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      if (r != 'confirm') return
      const inx = this.sqlList.findIndex((e) => e.value == this.sql)
      if (inx > -1) {
        this.sqlList.splice(inx, 1)
        localStorage.setItem('sqlList', JSON.stringify(this.sqlList))
        if (this.sqlList.length > 0) {
          this.sql = this.sqlList[0].value
        }
        this.$message.info('删除完成')
      }
    },

    async addToSqlList() {
      const inx = this.sqlList.findIndex((e) => e.value == this.sql)
      if (inx > -1) return this.$message.info('该SQL已经保存过了')
      try {
        const r = await this.$prompt('请输入语句说明', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (e) => {
            return e != ''
          },
          inputErrorMessage: '不能为空',
        })

        this.sqlList.push({ value: this.sql, label: r.value })
        localStorage.setItem('sqlList', JSON.stringify(this.sqlList))
      } catch (e) {
        this.$message.info('你取消了')
      }
    },
    addToDefault() {
      this.defaultSql = this.sql
      localStorage.setItem('defaultSql', this.defaultSql)
      this.$message.info('已保存为默认sql')
    },
    handleSelectChange(e) {
      console.log('handleSelectChange', e)
    },
    handleSqlFillBtn(k) {
      const sqlMap = {
        spininfo: `select  * from mqtt m where payload like '%SpinInfo%' and DateDiff(dd,newsj,getdate())=0 order by timestamp Desc`,
      }
      this.sql = sqlMap[k]
    },
    handleSizeChange(e) {
      console.log('handleSizeChange', e)
      this.pageInfo.pageSize = e
      this.getData()
    },
    handleCurrentChange(e) {
      this.pageInfo.pageNum = e
      this.getData()
    },
    async getData() {
      const loading = this.$loading({
        lock: true,
        text: '正在加载数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      try {
        const { pageNum: pagenum, pageSize: pagesize } = this.pageInfo
        const res = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: this.sql, pagenum, pagesize },
        })
        if (res.obj.list.length == 0) {
          loading.close()
          return
        }
        this.dataList = res.obj.list.map((e) => {
          const { PAGE_ROW_NUMBER, timestamp } = e
          return { PAGE_ROW_NUMBER, timestamp, ...JSON.parse(e.payload) }
        })

        const {
          endRow,
          hasNextPage,
          hasPreviousPage,
          isFirstPage,
          isLastPage,
          navigateFirstPage,
          navigateLastPage,
          navigatePages,
          navigatepageNums,
          nextPage,
          pageNum,
          pageSize,
          pages,
          prePage,
          size,
          startRow,
          total,
        } = res.obj
        this.pageInfo = {
          endRow,
          hasNextPage,
          hasPreviousPage,
          isFirstPage,
          isLastPage,
          navigateFirstPage,
          navigateLastPage,
          navigatePages,
          navigatepageNums,
          nextPage,
          pageNum,
          pageSize,
          pages,
          prePage,
          size,
          startRow,
          total,
        }
        this.propList = Object.keys(this.dataList[0]).filter((e) => ['SpinSpeed', 'SpinState', 'timestamp', 'Side', 'SpinVol'].indexOf(e) == -1)
        console.log('#####getData', this.dataList)
      } catch (e) {
        console.log('Error:', e)
      } finally {
        loading.close()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';
.page-wrap {
  padding: 10px 20px;
  box-sizing: border-box;
}

.sub-item {
  width: 48px;
  text-align: center;
  border-right: 1px #eee solid;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.sub-item-row {
  font-size: 10px;
  height: 14px;
  line-height: 14px;
}

.top-wrap {
  width: 800px;
}
.spin-status {
  margin-top: 10px;
  height: calc(100vh - 220px);
  border: 1px solid #eee;
}
.spin-list-row {
  // border-left: 1px solid #eee;
  // border-right: 1px solid #eee;
  display: flex;
}
.spin-list-col {
  width: 4%;
  height: 40px;
  padding: 4px;
  box-sizing: border-box;
}
.spin-list-item {
  width: 100%;
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  display: flex;
  font-size: 12px;
  align-items: center;
  justify-content: center;
}

.spin-list-title {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  letter-spacing: 1px;
}
::v-deep .el-select .el-select-dropdown .el-scrollbar {
  padding-bottom: 15px !important;
}
.el-table__body tr.current-row > td {
  background-color: #f7f193;
}
</style>
